package copy.filter;

import com.alibaba.fastjson.JSON;
import copy.com.BaseContext;
import copy.com.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义拦截器
 * 检查用户登录是否
 **/
@Slf4j
@WebFilter(filterName = "loginCheckFilter4.08", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符 AntPathMather
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次请求的URL
        String requestURI = request.getRequestURI();// /backend/index.html
        log.info("拦截器请求: {}", requestURI);


        String[] url = new String[]{
                //登录退出
                "/employee/login",
                "/employee/logout",
//                "/common/upload",
                //静态
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"

        };
        //判断本次请求是否需要处理
        boolean checks = check(url, requestURI);
        //如果不需要处理直接放行 check方法
        if (checks) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //判断employee登录状态，如果已经登录，直接放行
        if (request.getSession().getAttribute("emp") != null) {
            log.info("用户已经登录且id为:{}", request.getSession().getAttribute("emp"));
            Long empId = (Long) request.getSession().getAttribute("emp");
           /* ThreadLocal 同一个请求即同一个线程处理 可以取到存入的用户id
            在url拦截器中处理 是基于 无法判定哪一个请求会需要取出当前用户id 所以当url对所有的请求拦截处理时候
           * 对以已经登录过的该条请求 set 用户id 则该请求调用的所有方法都可以通过thereadLocal来拿用户id*/
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);
            return;


        }


        //判断user登录状态，如果已经登录，直接放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已经登录且id为:{}", request.getSession().getAttribute("user"));

            Long userID = (Long) request.getSession().getAttribute("user");

            BaseContext.setCurrentId(userID);

            filterChain.doFilter(request, response);
            return;

        }
        //如果未登录则返回未登录结果
//通过输出流方式向客户端页面响应数据
        //R对象转JSON由输出流输出
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 写一个check方法
     */
    public boolean check(String[] url, String requestURL) {
        for (String u : url) {
            boolean b = PATH_MATCHER.match(u, requestURL);
            if (b) {
                return true;
            }
        }
        return false;
    }
}
